<template>
  <!-- 新增/修改菜单的弹窗 -->
  <el-drawer v-model="dialogVisible" size="60%" @close="closeDialog(deptFormRef)">
    <template #title>
      <span class="flex items-center">
        <el-icon class="mr-1" :size="20" color="var(--el-color-primary)"><DocumentAdd /></el-icon>
        {{ dialogTitle }}
      </span>
    </template>
    <el-form ref="deptFormRef" :model="formData" :rules="rules" :label-width="formLabelWidth">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="上级部门" prop="parentId">
            <el-tree-select
              v-model="formData.parentId"
              :data="deptTreeData"
              placeholder="请选择上级部门"
              check-strictly
              :render-after-expand="false"
              :props="{ value: 'id', label: 'deptName', children: 'children' }"
              clearable
            >
            </el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="formData.deptName" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="部门代码" prop="deptCode">
            <el-input v-model="formData.deptCode" clearable :disabled="!!formData.id"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门全称" prop="fullName">
            <el-input v-model="formData.fullName" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="部门类型" prop="deptType">
            <el-select v-model="formData.deptType" clearable filterable>
              <el-option v-for="(item, index) in deptTypeDict" :key="index" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number style="width: 100%" v-model="formData.orderNum" :min="0" controls-position="right">
              <template #decrease-icon>
                <el-icon>
                  <Minus />
                </el-icon>
              </template>
              <template #increase-icon>
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="formData.leader" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="办公电话" prop="phone">
            <el-input v-model="formData.phone" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="formData.address" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮政编码" prop="postalCode">
            <el-input v-model="formData.postalCode" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="formData.email" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="6" resize="none" v-model="formData.remark" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button :loading="submitLoading" @click="closeDialog(deptFormRef)"> 取消 </el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSave(deptFormRef)"> 确认 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { getDictDataListByType } from "@/api/modules/dict";
import { Dept } from "@/api/interface";
import { addDept, getDeptConst, getDeptTree, updateDept } from "@/api/modules/dept";
import { Dict } from "@/api/interface/dict";

defineOptions({
  name: "DeptAdd"
});

const emits = defineEmits(["close"]);
const formLabelWidth = "100px";
const dialogTitle = ref("新增部门");
const dialogVisible = ref(false);
const deptFormRef = ref<FormInstance>();
const deptTypeDict = ref<Dict.IDictData[]>([]);
const formData = reactive<Dept.IDept>({
  address: "",
  deptCode: "",
  deptName: "",
  deptType: "",
  email: "",
  fullName: "",
  leader: "",
  orderNum: 0,
  parentId: undefined,
  phone: "",
  postalCode: "",
  remark: ""
});

const submitLoading = ref(false);

const rules = ref<FormRules<Dept.IDept>>({
  deptName: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  deptCode: [{ required: true, message: "请输入部门代码", trigger: "blur" }],
  orderNum: [{ required: true, message: "请输入显示排序", trigger: "blur" }],
  fullName: [{ required: true, message: "请输入部门全称", trigger: "blur" }],
  deptType: [{ required: true, message: "请选择部门类型", trigger: "change" }],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  postalCode: [{ pattern: /^[1-9]\d{5}$/, message: "请输入正确的邮政编码", trigger: "blur" }]
});

const deptTreeData = ref<Dept.IDept[]>([]);

const openDialog = async (type = "add", deptItem: any = {}) => {
  dialogTitle.value = type === "edit" ? "修改部门" : "新增部门";
  deptFormRef.value?.resetFields();
  if (type === "edit") {
    formData.id = deptItem.id;
    formData.parentId = deptItem.parentId == -1 ? undefined : deptItem.parentId;
    formData.deptName = deptItem.deptName;
    formData.deptCode = deptItem.deptCode;
    formData.fullName = deptItem.fullName;
    formData.deptType = deptItem.deptType;
    formData.orderNum = deptItem.orderNum;
    formData.leader = deptItem.leader;
    formData.phone = deptItem.phone;
    formData.address = deptItem.address;
    formData.postalCode = deptItem.postalCode;
    formData.email = deptItem.email;
    formData.remark = deptItem.remark;
    if (deptItem.parentId !== -1) {
      await getAllDept();
    }
  } else {
    const { data } = await getDeptConst();
    formData.deptCode = data?.deptCode || "";
    formData.orderNum = data?.orderNum || 0;
    if (deptItem.parentId) {
      formData.parentId = deptItem.parentId;
    }
    await getAllDept();
  }

  await getDeptTypeDict();
  dialogVisible.value = true;
};

const getAllDept = async () => {
  const { data } = await getDeptTree();
  console.log(data);
  deptTreeData.value = data;
};

const getDeptTypeDict = async () => {
  const { data } = await getDictDataListByType("SYSTEM_DEPT_TYPE");
  deptTypeDict.value = data;
};

const handleSave = (formRef: FormInstance | undefined) => {
  if (!formRef) return;
  submitLoading.value = true;
  formRef.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const saveURL = formData.id ? updateDept : addDept;
        await saveURL(formData);
        ElMessage.success("保存成功");
        closeDialog(formRef);
        submitLoading.value = false;
      } catch (e) {
        submitLoading.value = false;
      }
    } else {
      submitLoading.value = false;
    }
  });
};

const closeDialog = (formRef: FormInstance | undefined) => {
  if (!formRef) return;
  formData.id = undefined;
  formData.parentId = undefined;
  formRef.resetFields();
  dialogVisible.value = false;
  emits("close");
};
defineExpose({
  openDialog
});
</script>

<style scoped></style>
